<?php
/**
 * 我的预定记录
 * 相对路径: usr/recs.php
 * 作者: 15058593138@qq.com
 */

// 处理Ajax取消预定请求
if (isset($_GET['act']) && $_GET['act'] === 'cancel') {
    $unid = isset($_POST['unid']) ? safeStr($_POST['unid']) : '';
    $date = isset($_POST['date']) ? safeStr($_POST['date']) : '';
    
    if (empty($unid) || empty($date)) {
        jsonMsg(0, '参数错误');
    }
    
    $userId = $_SESSION['user_phone'];
    $db = new DB();
    $recTable = TB_PREFIX . 'recs_' . $date;
    
    // 验证是否是本人的预定
    $sql = "SELECT * FROM `{$recTable}` WHERE `unid` = '{$unid}' AND `usid` = '{$userId}'";
    if (!$db->getRow($sql)) {
        $db->close();
        jsonMsg(0, '预定记录不存在或无权操作');
    }
    
    // 更新状态为取消
    $result = $db->update($recTable, ['stats' => 0], "`unid` = '{$unid}'");
    $db->close();
    
    if ($result) {
        jsonMsg(1, '取消成功');
    } else {
        jsonMsg(0, '取消失败');
    }
}

// 处理Ajax查询预定列表
if (isset($_GET['act']) && $_GET['act'] === 'list') {
    $userId = $_SESSION['user_phone'];
    $db = new DB();
    
    // 查询最近7天的预定
    $dates = getDateRange(YU_TIAN);
    $allRecs = [];
    
    foreach ($dates as $date) {
        $recTable = TB_PREFIX . 'recs_' . $date;
        if ($db->tableExists($recTable)) {
            $sql = "SELECT * FROM `{$recTable}` WHERE `usid` = '{$userId}' ORDER BY `atime` DESC";
            $recs = $db->getAll($sql);
            
            foreach ($recs as $rec) {
                $allRecs[] = $rec;
            }
        }
    }
    
    // 获取教室名称
    $rooms = readJson('./inc/weici.json.php');
    $roomNames = [];
    foreach ($rooms as $room) {
        $roomNames[$room['room']] = $room['name'];
    }
    
    // 获取节次名称
    $jiecis = readJson('./inc/jieci.json.php');
    $jieciNames = [];
    foreach ($jiecis as $jieci) {
        $jieciNames[$jieci['code']] = $jieci['name'];
    }
    
    // 处理数据
    foreach ($allRecs as &$rec) {
        $rec['room_name'] = isset($roomNames[$rec['room']]) ? $roomNames[$rec['room']] : $rec['room'];
        $rec['jieci_name'] = isset($jieciNames[$rec['days']]) ? $jieciNames[$rec['days']] : $rec['days'];
        $rec['date_format'] = substr($rec['ijie'], 0, 4) . '-' . substr($rec['ijie'], 4, 2) . '-' . substr($rec['ijie'], 6, 2);
        $rec['status_text'] = $rec['stats'] == 1 ? '有效' : ($rec['stats'] == 0 ? '已取消' : '已征用');
    }
    
    $db->close();
    jsonMsg(1, '查询成功', $allRecs);
}

require_once './inc/head.php';
?>

<div class="container">
    <div class="table-wrapper">
        <div style="padding:15px; border-bottom:1px solid #eee;">
            <h3 style="display:inline-block;">我的预定</h3>
            <button class="btn btn-primary" style="float:right;" onclick="loadRecs()">刷新</button>
        </div>
        
        <table class="table">
            <thead>
                <tr>
                    <th>教室</th>
                    <th>日期</th>
                    <th>节次</th>
                    <th>座位号</th>
                    <th>状态</th>
                    <th>预定时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="recsList">
                <tr>
                    <td colspan="7" style="text-align:center;">加载中...</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<script>
    // 加载预定列表
    function loadRecs() {
        ajax('index.php?do=recs&act=list', {}, function(res) {
            if (res.code === 1) {
                renderRecs(res.data);
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 渲染预定列表
    function renderRecs(data) {
        const tbody = document.getElementById('recsList');
        
        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;">暂无预定记录</td></tr>';
            return;
        }
        
        let html = '';
        data.forEach(rec => {
            const canCancel = rec.stats == 1 && parseInt(rec.ijie) >= parseInt('<?php echo date("Ymd"); ?>');
            
            html += `<tr>
                <td>${rec.room_name}</td>
                <td>${rec.date_format}</td>
                <td>${rec.jieci_name}</td>
                <td>${rec.iwei}号</td>
                <td>
                    <span style="color:${rec.stats == 1 ? '#28a745' : (rec.stats == 0 ? '#999' : '#dc3545')}">
                        ${rec.status_text}
                    </span>
                </td>
                <td>${rec.atime}</td>
                <td>
                    ${canCancel ? `<button class="btn btn-danger btn-sm" onclick="cancelRec('${rec.unid}', '${rec.ijie}')">取消</button>` : ''}
                    ${rec.stats == 1 ? `<button class="btn btn-success btn-sm" onclick="showHema('${rec.hema}')">核验码</button>` : ''}
                </td>
            </tr>`;
        });
        
        tbody.innerHTML = html;
    }
    
    // 取消预定
    function cancelRec(unid, date) {
        showModal('确认取消', '<p>确定要取消这个预定吗？</p>', [
            {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
            {text: '确定', class: 'btn-danger', onclick: `doCancel('${unid}', '${date}')`}
        ]);
    }
    
    function doCancel(unid, date) {
        closeModal();
        showLoading();
        
        ajax('index.php?do=recs&act=cancel', {unid: unid, date: date}, function(res) {
            hideLoading();
            if (res.code === 1) {
                toast(res.msg, 'success');
                loadRecs();
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 显示核验码
    function showHema(hema) {
        showModal('预定核验码', `
            <div style="text-align:center; padding:20px;">
                <div style="font-size:32px; font-weight:bold; color:#1a73e8; margin:20px 0;">
                    ${hema}
                </div>
                <p style="color:#666; font-size:12px;">请妥善保管核验码</p>
            </div>
        `, [
            {text: '关闭', class: 'btn-secondary', onclick: 'closeModal()'}
        ]);
    }
    
    // 页面加载
    window.onload = function() {
        loadRecs();
    };
</script>

<?php require_once './inc/foot.php'; ?>